from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .models import User
from .serializers import UserSerializer, LoginSerializer
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import RefreshToken
from django.db import IntegrityError

class RegisterAPIView(APIView):
    """用户注册API - 默认注册为普通用户"""
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            try:
                user = serializer.save()
                return Response({
                    "code": 0,
                    "msg": "注册成功",
                    "data": {
                        "id": user.id,
                        "username": user.username,
                        "user_type": user.user_type  # 默认是'user'
                    }
                })
            except IntegrityError:
                # 当用户名已存在时会抛出IntegrityError异常
                return Response({
                    "code": 1,
                    "msg": "用户已存在",
                    "data": {"username": ["该用户名已被注册"]}
                }, status=status.HTTP_400_BAD_REQUEST)
        return Response({
            "code": 1,
            "msg": "注册失败",
            "data": serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)



class LoginAPIView(APIView):
    """用户登录API - 根据用户类型返回不同跳转地址"""
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            
            try:
                user = User.objects.get(username=username)
                if user.check_password(password):
                    # 更新最后登录时间
                    from django.utils import timezone
                    user.last_login = timezone.now()
                    user.save()
                    # 使用JWT生成token
                    refresh = RefreshToken.for_user(user)
                    access_token = str(refresh.access_token)
                    
                    # 根据用户类型返回不同的跳转地址
                    if user.user_type == 'admin':
                        redirect_url = '/backindex'  # 管理员后台
                    else:
                        redirect_url = '/'  # 普通用户首页
                    
                    return Response({
                        "code": 0,
                        "msg": "登录成功",
                        "data": {
                            "username": user.username,
                            "user_type": user.user_type,
                            "redirect_url": redirect_url,
                            "is_admin": user.user_type == 'admin',
                            "token": access_token,  # 只返回访问令牌
                            # "refresh_token": refresh_token  # 移除refresh_token
                        }
                    })
                else:
                    return Response({
                        "code": 1,
                        "msg": "密码错误"
                    }, status=status.HTTP_400_BAD_REQUEST)
            except User.DoesNotExist:
                return Response({
                    "code": 1,
                    "msg": "用户不存在"
                }, status=status.HTTP_400_BAD_REQUEST)
        
        return Response({
            "code": 1,
            "msg": "参数错误",
            "data": serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


class UserInfoAPIView(APIView):
    """获取用户信息"""
    # 修改为使用JWT认证
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
            # 返回用户实际信息
            user = request.user
            return Response({
                "code": 0,
                "msg": "获取用户信息成功",
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "user_type": user.user_type,
                    "avatar": user.avatar.url if user.avatar else None,
                    "date_joined": user.date_joined,
                    "last_login": user.last_login
                }
            })


class UserListAPIView(APIView):
    """获取用户列表 - 仅管理员可访问"""
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    
    
    def get(self, request):
        # 检查用户是否为管理员
        if request.user.user_type != 'admin':
            return Response({
                "code": 1,
                "msg": "无权限访问"
            }, status=status.HTTP_403_FORBIDDEN)
        
        # 获取搜索关键词和分页参数
        username = request.GET.get('username', '')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('pageSize', 10))
        
        # 构建查询集，添加搜索条件
        queryset = User.objects.all().order_by('-date_joined')
        if username:
            # 使用icontains进行不区分大小写的模糊搜索
            queryset = queryset.filter(username__icontains=username)
        
        # 计算总数
        total = queryset.count()
        
        # 实现分页
        start = (page - 1) * page_size
        end = start + page_size
        users = queryset[start:end]
        
        # 构建用户列表数据
        user_list = []
        for user in users:
            user_list.append({
                "id": user.id,
                "username": user.username,
                "userType": user.user_type,
                "registerTime": user.date_joined,
                "lastLoginTime": user.last_login
            })
        
        return Response({
            "code": 0,
            "msg": "获取用户列表成功",
            "data": user_list,
            "total": total,
            "pageSize": page_size,
            "currentPage": page
        })


class UserUpdateAPIView(APIView):
    """更新用户信息 - 仅管理员可访问"""
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    
    def put(self, request, user_id):
        # 检查用户是否为管理员
        if request.user.user_type != 'admin':
            return Response({
                "code": 1,
                "msg": "无权限访问"
            }, status=status.HTTP_403_FORBIDDEN)
        
        try:
            user = User.objects.get(id=user_id)
            
            # 获取更新数据
            username = request.data.get('username')
            password = request.data.get('password')
            user_type = request.data.get('userType')
            # 更新用户名
            if username:
                user.username = username
            
            # 更新密码
            if password:
                user.set_password(password)
            
            # 更新用户类型
            if user_type in ['admin', 'user']:
                user.user_type = user_type
            
            user.save()
            
            return Response({
                "code": 0,
                "msg": "更新成功",
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "user_type": user.user_type
                }
            })
            
        except User.DoesNotExist:
            return Response({
                "code": 1,
                "msg": "用户不存在"
            }, status=status.HTTP_404_NOT_FOUND)
        except IntegrityError:
            return Response({
                "code": 1,
                "msg": "用户名已存在",
                "data": {"username": ["该用户名已被使用"]}
            }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({
                "code": 1,
                "msg": "更新失败",
                "data": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserDeleteAPIView(APIView):
    """删除用户 - 仅管理员可访问"""
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    
    def delete(self, request, user_id):
        # 检查用户是否为管理员
        if request.user.user_type != 'admin':
            return Response({
                "code": 1,
                "msg": "无权限访问"
            }, status=status.HTTP_403_FORBIDDEN)
        
        try:
            user = User.objects.get(id=user_id)
            user.delete()
            return Response({
                "code": 0,
                "msg": "删除成功"
            })
        except User.DoesNotExist:
            return Response({
                "code": 1,
                "msg": "用户不存在"
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                "code": 1,
                "msg": "删除失败",
                "data": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserSelfUpdateAPIView(APIView):
    """更新当前用户自己的信息 - 所有登录用户可访问"""
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    
    def put(self, request):
        try:
            # 获取当前登录用户
            user = request.user
            
            # 获取更新数据
            username = request.data.get('username')
            password = request.data.get('password')
            
            # 更新用户名
            if username:
                user.username = username
            
            # 更新密码
            if password:
                user.set_password(password)
            
            user.save()
            
            return Response({
                "code": 0,
                "msg": "更新成功",
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "user_type": user.user_type
                }
            })
            
        except IntegrityError:
            return Response({
                "code": 1,
                "msg": "用户名已存在",
                "data": {"username": ["该用户名已被使用"]}
            }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({
                "code": 1,
                "msg": "更新失败",
                "data": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)